package com.ddxz.demo.shiro.jwt.service.impl;

import com.ddxz.demo.shiro.jwt.dto.LoginInfo;
import com.ddxz.demo.shiro.jwt.entity.UserEntity;
import com.ddxz.demo.shiro.jwt.mapper.ShiroMapper;
import com.ddxz.demo.shiro.jwt.service.ShiroService;
import com.ddxz.tool.core.common.DdxzJwtUtil;
import com.ddxz.tool.core.convert.StringUtil;
import com.ddxz.tool.web.dto.DdxzResponse;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * class description
 *
 * @author 朱宗刚
 * @version 1.0.0
 * @date 2020/11/25
 */

@Service
public class ShiroServiceImpl implements ShiroService {
    @Override
    public DdxzResponse login(LoginInfo info) {
        String password = mapper.getPasswordByName(info.getUsername());
        if(StringUtil.isEmpty(password)) {
            return DdxzResponse.correct("用户不存在");
        }

        if(!password.equals(info.getPassword())) {
            return DdxzResponse.correct("用户名或密码错误");
        }

        Map<String, Object> body = new HashMap<>(2);
        body.put("username", info.getUsername());
        body.put("company", "ddxz");
        return DdxzResponse.correct(jwtUtil.getToken(body));
    }

    @Override
    public DdxzResponse getUserInfo(String userId) {
        UserEntity entity = mapper.getEntityByName(userId);
        return DdxzResponse.correct(entity);
    }

    @Override
    public DdxzResponse getDeptInfo(String deptId) {
        return DdxzResponse.correct("获取部门详情成功");
    }

    @Override
    public DdxzResponse userList(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Page<UserEntity> entitys = mapper.getUserList();
        return DdxzResponse.correct(entitys);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DdxzResponse saveUser(UserEntity entity) {
        if(null != mapper.getPasswordByName(entity.getUsername())) {
            return DdxzResponse.correct("用户名以存在");
        }

        if(null != mapper.getEntityByName(entity.getId())) {
            return DdxzResponse.correct("主键冲突");
        }

        mapper.saveUser(entity);
        return DdxzResponse.correct("保存成功");
    }

    private final ShiroMapper mapper;
    private DdxzJwtUtil jwtUtil = new DdxzJwtUtil(6000000);

    public ShiroServiceImpl(ShiroMapper mapper) {
        this.mapper = mapper;
    }
}
